package hottargui.domain.semi;
import hottargui.domain.*;

public class SemiWinnerStrategyImpl implements WinnerStrategy {

	private Board _board;
	private StateMachine  _sm;

	public SemiWinnerStrategyImpl(StateMachine sm) {
		_sm = sm; 
		_board = sm.getBoard();
	}

	public PlayerColor getTheWinner(){
		return getWinnerSecundaryObjectiv();
	}

	public PlayerColor[] getWinnerPrimaryObjectiv(){
		PlayerColor[] _primaryWinners = new PlayerColor[4];
		int i = 0;

		int r_red = _board.getRevenue(PlayerColor.Red);
		int r_blue = _board.getRevenue(PlayerColor.Blue);
		int r_green = _board.getRevenue(PlayerColor.Green);
		int r_yellow = _board.getRevenue(PlayerColor.Yellow);

		// add winner on primary objective to the winner array 
		if ((r_red >= r_blue) && (r_red >= r_green) && (r_red >= r_yellow) ) {
			_primaryWinners[i] = PlayerColor.Red;
			i ++;
		}

		if ((r_blue >= r_red) && (r_blue >= r_green) && (r_blue >= r_yellow)) {
			_primaryWinners[i] = PlayerColor.Blue;
			i++;
		}

		if ((r_green >= r_red) && (r_green >= r_blue) && (r_green >= r_yellow)) {
			_primaryWinners[i] = PlayerColor.Green;
			i++;
		}

		if ((r_yellow >= r_red) && (r_yellow >= r_blue) && (r_yellow >= r_green)) {
			_primaryWinners[i] = PlayerColor.Yellow;
			i++;
		}
		return _primaryWinners;
	}


	public PlayerColor getWinnerSecundaryObjectiv() {
		ModifiablePlayer highRevenuePlayer;
		ModifiablePlayer nextPlayer;
		boolean identicalTreasury;
		PlayerColor[] _primaryWinner = getWinnerPrimaryObjectiv();

		//no Winner found i primary objective		
		if (_primaryWinner[0] == null) {
			return PlayerColor.None;
		}
		if ((_primaryWinner[0] != null) && (_primaryWinner[1] == null))
			return PlayerColor.Red;//_primaryWinner[0];

		highRevenuePlayer = _sm.getPlayer(_primaryWinner[0]);
		identicalTreasury = false;

		for (int i = 0; i < _primaryWinner.length; i ++){
			if (i == 0) {
				highRevenuePlayer = _sm.getPlayer(_primaryWinner[0]);
				identicalTreasury = false;
			}
			else {	
				nextPlayer = _sm.getPlayer(_primaryWinner[i]);
				if (nextPlayer.getCoins() > highRevenuePlayer.getCoins()){
					highRevenuePlayer = _sm.getPlayer(_primaryWinner[i]);
					identicalTreasury = false;
				}
				else{
					if (nextPlayer.getCoins() == highRevenuePlayer.getCoins()){
						identicalTreasury = true;
					}else{
						identicalTreasury = false;
					}
				}
			}
		}
		if (identicalTreasury){
			return PlayerColor.None;
		} 
		else{	
			return highRevenuePlayer.getColor();
		}
	}
}
